//
//  BPLoginViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/9/1.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPRegisterViewController.h"
#import "BPRegisterAccountParam.h"
#import "BPAccount.h"
#import "AccountTool.h"
#import "BPForgetPasswordViewController.h"
#import "orderViewController.h"
#import "BPhttpTool.h"
#import "MJExtension.h"
#import "BPProductMakeViewController.h"

#define messageBtnColor BPColor(244, 133, 142)

//计时器间隔秒数
#define maxSecond 120

//获取验证码
#define authcodeGetTitle @"获取验证码"

@interface BPRegisterViewController ()<UITextFieldDelegate,UIScrollViewDelegate>{
    int _currentSecond;//当前的秒数
    
    BPRegisterAccountParam *_paramAccount;
    
    BPAccount *_account;
}

@end

@implementation BPRegisterViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self drawUIView];
    [self setUpNav];
    //2.初始化计时器的当前秒数
    _currentSecond = maxSecond;
    _paramAccount = [[BPRegisterAccountParam alloc] init];
    _account = [[BPAccount alloc] init];
    
    [self setUpAccountAndPassword];
    // Do any additional setup after loading the view.
}

- (void)setUpNav
{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(5.0f, 20.0f, 50.0f, 50.0f);
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(dismissLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
}

- (void)dismissLogin
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)drawUIView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    _scrollView.backgroundColor = [UIColor whiteColor];
    _scrollView.alwaysBounceVertical = YES;
    [self.view addSubview:_scrollView];
    UITapGestureRecognizer *hideKEY= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    [_scrollView addGestureRecognizer:hideKEY];
    _scrollView.delegate = self;
    [_scrollView addSubview:self.headView];
    
    self.view.backgroundColor = [UIColor whiteColor];
}

- (UIView *)headView
{
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BPScreenW, 150.0f)];
        _headView.backgroundColor = [UIColor whiteColor];
//        _headView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"LoginImage"]];
     
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(_headView.frame.size.width / 2 - 100, 0, 200, 140)];
        imageV.image = [UIImage imageNamed:@"LoginImage"];
        [_headView addSubview:imageV];
        
        UIImageView *langXian = [[UIImageView alloc] initWithFrame:CGRectMake(0, _headView.frame.size.height - 5, self.headView.frame.size.width, 5)];
        langXian.image = [UIImage imageNamed:@"波纹线"];
        [_headView addSubview:langXian];
        
    }
    return _headView;
}

- (void)setUpAccountAndPassword
{
    NSArray *placeArry = [NSArray arrayWithObjects:@"请输入您的手机号",@"输入验证码",@"请输入6~20位密码", nil];
    
    CGFloat textY = CGRectGetMaxY(_headView.frame);
    CGFloat textH = 47.0f;
    CGFloat textX = 20.0f;
    CGFloat textW = BPScreenW - 40.0f;
    
    
    UILabel *add = [[UILabel alloc] initWithFrame:CGRectMake(textX, textY, 50, textH)];
    add.text = @"账号:";
    add.alpha = 0.5;
    add.font = [UIFont systemFontOfSize:18];
    [_scrollView addSubview:add];
    
    _phoneNmuber = [[UITextField alloc] initWithFrame:CGRectMake(textX + 50, textY, textW, textH)];
    _phoneNmuber.delegate = self;
    _phoneNmuber.placeholder = placeArry[0];
    _phoneNmuber.keyboardType = UIKeyboardTypeNumberPad;
    [_scrollView addSubview:_phoneNmuber];
    
    
    _message = [[UITextField alloc] init];
//    _message.frame = _phoneNmuber.bounds;
    _message.frame = CGRectMake(textX + 50, textY, textW - 100, textH);
    _message.y = _phoneNmuber.y + textH;
    _message.x = textX + 50;
    _message.delegate = self;
    _message.placeholder = placeArry[1];
    _message.keyboardType = UIKeyboardTypeNumberPad;
    [_scrollView addSubview:_message];
    
    _messageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _messageBtn.backgroundColor = [UIColor yellowColor];
    [_messageBtn setTitle:authcodeGetTitle forState:UIControlStateNormal];
    _messageBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    [_messageBtn setBackgroundColor:messageBtnColor];
    _messageBtn.size = CGSizeMake(80.0f, 21.0f);
    _messageBtn.x = BPScreenW - _messageBtn.width - BPStatusCellInset;
    _messageBtn.y = _message.y + 10;
    [_messageBtn.layer setCornerRadius:11.0f];
    [_scrollView addSubview:_messageBtn];
    [_messageBtn addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    UILabel *mima = [[UILabel alloc] initWithFrame:CGRectMake(textX, _message.y + textH, 50, textH)];
    mima.text = @"密码:";
    mima.alpha = 0.5;
    mima.font = [UIFont systemFontOfSize:18];
    [_scrollView addSubview:mima];
    
    _passWord = [[UITextField alloc] init];
    _passWord.frame = _message.bounds;
    _passWord.y = _message.y + textH;
    _passWord.x = textX + 50;
    _passWord.delegate = self;
    _passWord.placeholder = placeArry[2];
    _passWord.secureTextEntry = YES;
    [_scrollView addSubview:_passWord];
    
    _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_registerBtn setTitle:@"注册并登录" forState:UIControlStateNormal];
    [self addBtn:_registerBtn];
    //_registerBtn.center = CGPointMake(BPScreenW / 0.2, _passWord.y + _passWord.height + 63.0f);
    _registerBtn.frame = CGRectMake(25, _passWord.y + _passWord.height + 63.0f, self.view.frame.size.width - 50, 30);
    [_registerBtn addTarget:self action:@selector(registerAccountreal) forControlEvents:UIControlEventTouchUpInside];
    
//    UIButton *forget = [UIButton buttonWithType:UIButtonTypeCustom];
//    [forget setTitle:@"忘记密码" forState:UIControlStateNormal];
//    [self addBtn:forget];
//    forget.center = CGPointMake((BPScreenW / 2.0), _registerBtn.y + _registerBtn.height + 30.0f);
//    [forget addTarget:self action:@selector(forgetPass) forControlEvents:UIControlEventTouchUpInside];
    _scrollView.contentSize = CGSizeMake(BPScreenW, _registerBtn.height + _registerBtn.y);
    for (int i = 0; i < 3; i ++) {
        BPLineView *line = [[BPLineView alloc] initWithFrame:CGRectMake(60, textY + textH * (i+1), BPScreenW, 0.7)];
        [_scrollView addSubview:line];
    }
}

- (void)addBtn:(UIButton *)button
{
    button.size = CGSizeMake(106.0f, 32.0f);
    button.backgroundColor = BPGlobaThemeColor;
    [button.layer setCornerRadius:17.0f];
    [_scrollView addSubview:button];
}

- (void)sendMessage
{
    if ([self checkPhoneNumber]==YES) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.f
                                                  target:self
                                                selector:@selector(updateAuthcodeBtn:)
                                                userInfo:nil
                                                 repeats:YES];
        [_timer fire];
        
        [BPhttpTool get:[NSString stringWithFormat:@"%@user/verify/mobile/%@",BPhttp,_phoneNmuber.text] params:nil success:^(id responseObj) {
            if (responseObj != nil) {
                _paramAccount.verifycode = responseObj[@"code"];
                BPLog(@"%@",_paramAccount.code);
            }
        } failure:^(NSError *error) {
            BPLog(@"验证码获取失败");
        }];
        
//        [AccountTool receiveMessageCode:_phoneNmuber.text success:^(BPRegisterAccountParam *result) {
//            _paramAccount.verifycode = result.code;
//            
//        } failure:^(NSError *error) {
//            BPLog(@"验证码获取失败");
//        }];
    }
}

- (void)forgetPass
{
    BPForgetPasswordViewController *forget = [[BPForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:forget animated:YES];
}

- (void)updateAuthcodeBtn:(NSTimer *)time
{
    if (_currentSecond <= 0) {
        [self endTimer];
        _currentSecond = maxSecond;
        _messageBtn.enabled = YES;
        [_messageBtn setTitle:authcodeGetTitle forState:UIControlStateNormal];
        [_messageBtn setTitle:authcodeGetTitle forState:UIControlStateDisabled];
        [_messageBtn setTitle:authcodeGetTitle forState:UIControlStateHighlighted];
    }
    else
    {
        _messageBtn.enabled = NO;
        NSString *timeTipInfo = [NSString stringWithFormat:@"%i秒后获取",_currentSecond];
        [_messageBtn setTitle:timeTipInfo forState:UIControlStateNormal];
        [_messageBtn setTitle:timeTipInfo forState:UIControlStateDisabled];
        [_messageBtn setTitle:timeTipInfo forState:UIControlStateHighlighted];
    }
    _currentSecond--;
}

#pragma mark 停止计时器
-(void)endTimer
{
    if (_timer)
    {
        [_timer invalidate];
        _timer = nil;
    }
}


- (void)registerAccountreal
{
    if ([self checkPhoneNumber] == YES && [_message.text isEqualToString:_paramAccount.verifycode] == YES && [self isStrEmpty:_passWord.text] == NO) {
        _paramAccount.username = _phoneNmuber.text;
        _paramAccount.password = _passWord.text;
        NSLog(@"%@",_paramAccount.verifycode);
        [AccountTool postAccountWithParam:_paramAccount success:^(BPAccount *result) {
                        
            if ([result.uid intValue] > 0) {
                _account.uid = result.uid;
                _account.mobile = _paramAccount.username;
                _account.password = _paramAccount.password;
                //保存账号信息
                [AccountTool save:_account];
                [[NSUserDefaults standardUserDefaults] setObject:_account.mobile forKey:@"userPhone"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self SZBpopVC];
                //回到提交订单页面
            }else{
                [self showAlertWithMessage:result.info];
            }
//            else if ([result.uid intValue] == -3){
//                [self showAlertWithMessage:@"账号已注册"];
//                
//            }else{
//
//            //账号注册不成功
//                [self showAlertWithMessage:@"账号注册失败"];
//            }
        } failure:^(NSError *error) {
            [self showAlertWithMessage:@"网络错误"];
        }];
    }else{
        if ([_message.text isEqualToString:_paramAccount.verifycode] == NO) {
            [self showAlertWithMessage:@"验证码有误"];
            return;
        }
        if ([self isStrEmpty:_passWord.text] == YES){
            [self showAlertWithMessage:@"密码为空"];
        }
    
    }
}

- (void)SZBpopVC
{
    if (_isHome == YES) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        _regblock();
    }else{
        for (UIViewController *temp in self.navigationController.viewControllers) {
            if ([temp isKindOfClass:[BPProductMakeViewController class]]) {
                [self.navigationController popToViewController:temp animated:YES];
                _regblock();
            }
        }
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offsetY = frame.origin.y + frame.size.height - (self.view.frame.size.height - 286.0);
    if (offsetY > 0) {
        [UIView animateWithDuration:0.3f animations:^{
        self.view.frame = CGRectMake(0, -offsetY, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
    [UIView commitAnimations];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
    self.view.frame =  CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

- (BOOL)checkPhoneNumber
{
    NSString *phoneNumber = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumber];
    
    BOOL isMatch = [pred evaluateWithObject:_phoneNmuber.text];
    
    if (!isMatch) {
        [self showAlertWithMessage:@"请输入正确的手机号码"];
        return NO;
    }else
    {
        return YES;
    }
}

- (void)showAlertWithMessage:(NSString *)message
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
    [alert show];
}

//判断text是否为空
-(BOOL)isStrEmpty:(NSString*)str
{
    if (str == nil || str == NULL)
    {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    if ([str length] <= 0)
    {
        return YES;
    }
    return NO;
}

- (void)hideKeyBoard
{
    [self.view endEditing:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
